package com.printf.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Environment;
import android.util.Log;

import com.printf.utils.BinaryConversionUtil;
import com.printf.utils.ImageUtil;

public class PrintfCPCLManager {

    private Context context;
    private BluetoothManager bluetoothManager;

    static class PrintfCPCLManagerHolder {
        private static PrintfCPCLManager instance = new PrintfCPCLManager();
    }

    public static PrintfCPCLManager getInstance(final Context context) {
        if (PrintfCPCLManager.PrintfCPCLManagerHolder.instance.context == null) {
            PrintfCPCLManager.PrintfCPCLManagerHolder.instance.context
                    = context.getApplicationContext();
            PrintfCPCLManager.PrintfCPCLManagerHolder.instance.bluetoothManager = BluetoothManager.getInstance(context);
        }
        return PrintfCPCLManager.PrintfCPCLManagerHolder.instance;
    }

    public void testPrintf(Bitmap bitmap){
        StringBuilder cmd = new StringBuilder();
        cmd.append("! 0 200 200 160 1\n")
                .append("PAGE-WIDTH 160\n")
                .append("BG 0 0 0\n")
                .append(conversionBitmapToCMD(bitmap,0,0,15,15))
                .append("FORM\nPRINT\n");
        String s = cmd.toString();
        bluetoothManager.write(s.getBytes());
    }

//    public void testPrintf(Bitmap bitmap){
//
//        bluetoothManager.write("! 0 200 200 400 1\n".getBytes());
//        bluetoothManager.write("PAGE-WIDTH 576\n".getBytes());
//        bluetoothManager.write("BG 0 0 0\n".getBytes());
//
//        printfImage(bitmap,0,0,20,20);
//
//        bluetoothManager.write("FORM\nPRINT\n".getBytes());
//
//    }

    /**
     * 打印图片
     */
    public void printfImage(Bitmap bitmap, int xMM, int yMM, int bitmapWMM, int bitmapHMM){
        //需要先处理一下图片
        if (bitmap.getHeight() != bitmapHMM * 8 || bitmap.getWidth() != bitmapWMM * 8) {
            bitmap = handleBitmap(bitmap, bitmapWMM * 8, bitmapHMM * 8, 0);
            String path = Environment.getExternalStoragePublicDirectory("")
                    + "/com.mht/";
            String s = ImageUtil.saveBitmap(bitmap, "cpcl.png", path);
        }

        StringBuilder cmd = new StringBuilder();
        cmd.append("CG ")
                .append(bitmap.getWidth() / 8).append(" ")
                .append(bitmap.getHeight()).append(" ")
                .append(xMM * 8).append(" ")
                .append(yMM * 8).append(" ");

        bluetoothManager.write(cmd.toString().getBytes());

        byte[] bytes = convertToBMW(bitmap, 128);

        bluetoothManager.write(bytes);
        bluetoothManager.write("\n".getBytes());

    }
    /**
     * 图片二值化
     *
     * @param bmp
     * @return
     */
    public static byte[] convertToBMW(Bitmap bmp, int concentration) {
        if (concentration <= 0 || concentration >= 255) {
            concentration = 128;
        }
        int width = bmp.getWidth(); // 获取位图的宽
        int height = bmp.getHeight(); // 获取位图的高
        byte[] bytes = new byte[(width) / 8 * height];
        int[] p = new int[8];
        int n = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width / 8; j++) {
                for (int z = 0; z < 8; z++) {
                    int grey = bmp.getPixel(j * 8 + z, i);
                    int red = ((grey & 0x00FF0000) >> 16);
                    int green = ((grey & 0x0000FF00) >> 8);
                    int blue = (grey & 0x000000FF);
                    int gray = (int) (0.29900 * red + 0.58700 * green + 0.11400 * blue); // 灰度转化公式
//                    int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
                    if (gray <= concentration) {
                        gray = 1;//黑色
                    } else {
                        gray = 0;//白色

                    }
                    p[z] = gray;
                }
                byte value = (byte) (p[0] * 128 + p[1] * 64 + p[2] * 32 + p[3] * 16 + p[4] * 8 + p[5] * 4 + p[6] * 2 + p[7]);
                bytes[width / 8 * i + j] = value;
            }
        }
        return bytes;
    }
    /**
     * 将Bitmap对象转化成需要的指令
     * EG 2 16 90 45 F0F0F0F0F0 F0F0F00F0F 0F0F0F0F0F 0FF0F0F0F0 F0F0F0F00F 0F0F0F0F0F 0F0F
     */
    public String conversionBitmapToCMD(Bitmap bitmap, int xMM, int yMM, int bitmapWMM, int bitmapHMM) {

        //需要先处理一下图片
        if (bitmap.getHeight() != bitmapHMM * 8 || bitmap.getWidth() != bitmapWMM * 8) {
            bitmap = handleBitmap(bitmap, bitmapWMM * 8, bitmapHMM * 8, 0);
            String path = Environment.getExternalStoragePublicDirectory("")
                    + "/com.mht/";
            String s = ImageUtil.saveBitmap(bitmap, "cpcl.png", path);
        }

        StringBuilder cmd = new StringBuilder();
        cmd.append("EG ")
                .append(bitmap.getWidth() / 8).append(" ")
                .append(bitmap.getHeight()).append(" ")
                .append(xMM * 8).append(" ")
                .append(yMM * 8).append(" ");

        int width = bitmap.getWidth(); // 获取位图的宽
        int height = bitmap.getHeight(); // 获取位图的高
        int[] p = new int[8];
        int n = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width / 8; j++) {
                for (int z = 0; z < 8; z++) {
                    int grey = bitmap.getPixel(j * 8 + z, i);
                    int red = ((grey & 0x00FF0000) >> 16);
                    int green = ((grey & 0x0000FF00) >> 8);
                    int blue = (grey & 0x000000FF);
                    int gray = (int) (0.29900 * red + 0.58700 * green + 0.11400 * blue); // 灰度转化公式
//                    int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
                    if (gray <= 128) {
                        gray = 1;//黑色
                    } else {
                        gray = 0;//白色

                    }
                    p[z] = gray;
                }
                n++;
                byte value = (byte) (p[0] * 128 + p[1] * 64 + p[2] * 32 + p[3] * 16 + p[4] * 8 + p[5] * 4 + p[6] * 2 + p[7]);
                cmd.append(BinaryConversionUtil.byteToHexFun_1(value));
            }
        }
        Log.e("TAG","n:" + n);
        cmd.append("\n");
        return cmd.toString();
    }

    /**
     * 处理图片的大小
     *
     * @param bitmap
     * @param newBitmapW
     * @param newBitmapH
     * @return
     */
    private Bitmap handleBitmap(Bitmap bitmap, float newBitmapW, float newBitmapH, int rotate) {

        int height = bitmap.getHeight();
        int width = bitmap.getWidth();

        // 计算缩放比例
        float scaleWidth = ((float) newBitmapW) / width;
        float scaleHeight = ((float) newBitmapH) / height;

        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        //先旋转，后缩小
        if (rotate % 360 != 0) {
            matrix.setRotate(rotate, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        }

        matrix.postScale(scaleWidth, scaleHeight);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        return bitmap;
    }


}
